﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;

namespace StudyCompanion.Commons.Authorize;

public class TokenProvider
{
    /// <summary>
    ///     根据用户获取token
    /// </summary>
    /// <param name="userInfo">用户信息</param>
    /// <param name="appid">应用Id</param>
    /// <returns></returns>
    public static string CreateToken(JwtOption jwt, List<Claim> claims)
    {
        var key = Encoding.UTF8.GetBytes(jwt.Secret);
        var authTime = DateTime.UtcNow; //授权时间
        var expires = authTime.Add(TimeSpan.FromMinutes(jwt.Expire)); //过期时间
        var tokenHandler = new JwtSecurityTokenHandler();

        claims.Add(new Claim(ClaimConst.Issuer, jwt.Issuer));
        claims.Add(new Claim(ClaimConst.AuthTime, DateTime.Now.ToString()));

        var tokenDescripor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(claims),
            Expires = expires,
            Audience = jwt.Audience,
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
        };
        var token = tokenHandler.CreateToken(tokenDescripor);
        return tokenHandler.WriteToken(token);
    }
}